package com.apobates.jforum.grief.aurl.convertor;

import com.apobates.jforum.grief.aurl.core.AUrlMeta;
import com.apobates.jforum.grief.aurl.selector.DomainStringSelector;
import com.apobates.jforum.grief.aurl.spring.StringUtils;

/**
 * URI字符串的转换器
 */
public class URIStringConvertor implements AUrlMetaConvertor<String>{
    @Override
    public String convert(AUrlMeta aUrlMeta) throws IllegalStateException {
        StringBuilder uriBuilder = new StringBuilder();
        // schema:domain:port
        uriBuilder.append(getDomainString(aUrlMeta));
        //
        String path = aUrlMeta.getPath();
        if (StringUtils.hasLength(path)) {
            if (uriBuilder.length() != 0 && path.charAt(0) != _PATH_DELIMITER) {
                uriBuilder.append(_PATH_DELIMITER);
            }
            uriBuilder.append(path);
        }
        String query = aUrlMeta.getQuery();
        if (query != null) {
            uriBuilder.append('?').append(query);
        }
        if (aUrlMeta.getFragment() != null) {
            uriBuilder.append('#').append(aUrlMeta.getFragment());
        }
        return uriBuilder.toString();
    }

    private String getDomainString(AUrlMeta aUrlMeta){
        DomainStringSelector dss = new DomainStringSelector(aUrlMeta);
        return dss.getSingle(()->null);
    }
}
